package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/7/7 21:57
 * https://leetcode.cn/problems/longest-increasing-path-in-a-matrix/
 */
public class Title329II {

    int n, m;
    int[][] maxPath;

    public int longestIncreasingPath(int[][] matrix) {
        n = matrix.length;
        m = matrix[0].length;
        maxPath = new int[n][m];
        int max = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                max = Math.max(max, dfs(matrix, i, j, -1));
            }
        }
        return max;
    }

    private int dfs(int[][] matrix, int i, int j, int pre) {
        if (i < 0 || i >= n || j < 0 || j >= m || matrix[i][j] <= pre) {
            return 0;
        }
        if (maxPath[i][j] != 0) {
            return maxPath[i][j];
        }
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        int max = 0;
        for (int k = 0; k < 4; k++) {
            max = Math.max(max, dfs(matrix, i + dx[k], j + dy[k], matrix[i][j]));
        }
        maxPath[i][j] = max + 1;
        return max;
    }

    public static void main(String[] args) {

    }
}
